/*
Copyright 2024 liuzw.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package controller

import (
	"context"
	corev1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/errors"
	"k8s.io/client-go/util/retry"
	resources "nginxcrdoperator/internal/controller/resource"
	"reflect"

	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/util/json"
	ctrl "sigs.k8s.io/controller-runtime"
	"sigs.k8s.io/controller-runtime/pkg/client"
	"sigs.k8s.io/controller-runtime/pkg/log"

	appsv1 "k8s.io/api/apps/v1"
	nginxv1 "nginxcrdoperator/api/v1"
)

var (
	oldSpecAnnotation = "old/spec"
)

// CrdNginxServiceReconciler reconciles a CrdNginxService object
type CrdNginxServiceReconciler struct {
	client.Client
	Scheme *runtime.Scheme
}

// +kubebuilder:rbac:groups=nginx.ictnj.cn,resources=crdnginxservices,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=nginx.ictnj.cn,resources=crdnginxservices/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=nginx.ictnj.cn,resources=crdnginxservices/finalizers,verbs=update

// Reconcile is part of the main kubernetes reconciliation loop which aims to
// move the current state of the cluster closer to the desired state.
// TODO(user): Modify the Reconcile function to compare the state specified by
// the CrdNginxService object against the actual cluster state, and then
// perform operations to make the cluster state reflect the state specified by
// the user.
//
// For more details, check Reconcile and its Result here:
// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.19.0/pkg/reconcile
func (r *CrdNginxServiceReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
	logger := log.FromContext(ctx, "namespace", req.NamespacedName)

	// TODO(user): your logic here
	var nginxService nginxv1.CrdNginxService
	err := r.Get(ctx, req.NamespacedName, &nginxService)
	if err != nil {
		// Ignore when the nginxService is deleted
		if client.IgnoreNotFound(err) != nil {
			logger.Info("检测到 NginxService 被删除")
			return ctrl.Result{}, err
		}
		logger.Error(err, "CrdNginxService异常")
		return ctrl.Result{}, nil
	}
	logger.Info("检测到 nginxService: ", "nginxService", req.NamespacedName, "yaml", nginxService)
	// If no, create an associated resource
	// If yes, determine whether to update it
	deploy := &appsv1.Deployment{}
	if err := r.Get(ctx, req.NamespacedName, deploy); err != nil && errors.IsNotFound(err) {
		// 1. 解析 annotations
		data, _ := json.Marshal(nginxService.Spec)
		if nginxService.Annotations != nil {
			nginxService.Annotations[oldSpecAnnotation] = string(data)
		} else {
			nginxService.Annotations = map[string]string{oldSpecAnnotation: string(data)}
		}
		if err := retry.RetryOnConflict(retry.DefaultRetry, func() error {
			return r.Client.Update(ctx, &nginxService)
		}); err != nil {
			return ctrl.Result{}, err
		}
		// Creating Associated Resources
		// 2. 创建 deploy
		deploy := resources.NewDeploy(&nginxService)
		if err := r.Client.Create(ctx, deploy); err != nil {
			logger.Info("创建 nginxService Deploy", "deployName", deploy.Name)
			return ctrl.Result{}, err
		}
		// 3. 创建 service
		service := resources.NewService(&nginxService)
		if err := r.Create(ctx, service); err != nil {
			logger.Info("创建 nginxService Service", "serviceName", service.Name)
			return ctrl.Result{}, err
		}
		return ctrl.Result{}, nil
	}
	// Gets the spec of the original AppService object
	oldspec := nginxv1.CrdNginxServiceSpec{}
	if err := json.Unmarshal([]byte(nginxService.Annotations[oldSpecAnnotation]), &oldspec); err != nil {
		return ctrl.Result{}, err
	}
	// The current spec is inconsistent with the old object and needs to be updated
	// Otherwise return
	if !reflect.DeepEqual(nginxService.Spec, oldspec) {
		// Update associated resources
		newDeploy := resources.NewDeploy(&nginxService)
		oldDeploy := &appsv1.Deployment{}
		if err := r.Get(ctx, req.NamespacedName, oldDeploy); err != nil {
			return ctrl.Result{}, err
		}
		oldDeploy.Spec = newDeploy.Spec
		if err := retry.RetryOnConflict(retry.DefaultRetry, func() error {
			return r.Client.Update(ctx, oldDeploy)
		}); err != nil {
			return ctrl.Result{}, err
		}

		newService := resources.NewService(&nginxService)
		oldService := &corev1.Service{}
		if err := r.Get(ctx, req.NamespacedName, oldService); err != nil {
			return ctrl.Result{}, err
		}
		// You need to specify the ClusterIP to the previous one; otherwise, an error will be reported during the update
		newService.Spec.ClusterIP = oldService.Spec.ClusterIP
		oldService.Spec = newService.Spec
		if err := retry.RetryOnConflict(retry.DefaultRetry, func() error {
			return r.Client.Update(ctx, oldService)
		}); err != nil {
			return ctrl.Result{}, err
		}
	}
	return ctrl.Result{}, nil
}

// SetupWithManager sets up the controller with the Manager.
func (r *CrdNginxServiceReconciler) SetupWithManager(mgr ctrl.Manager) error {
	return ctrl.NewControllerManagedBy(mgr).
		For(&nginxv1.CrdNginxService{}).
		Named("crdnginxservice").
		Complete(r)
}
